package singleton.v1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 使用静态内部类实现单例，在序列化对象时，还是多例的
 * @author wanglong
 * @createDate: 2019年3月24日 下午10:53:38
 */
public class SingletonUnSafe3  implements Serializable{
	
	private static final long serialVersionUID = -6188937531463680896L;


	private static class staticInner{
		private static SingletonUnSafe3 object = new SingletonUnSafe3();
	}
	
	private SingletonUnSafe3() {}
	
	private static SingletonUnSafe3 getInstance() {
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return staticInner.object;
	}
	
	
	public static void main(String[] args) {
		
		SingletonUnSafe3 object = new SingletonUnSafe3();
		/**
		 * 序列化
		 */
		try {
			FileOutputStream fos = new FileOutputStream(new File("SingletonUnSafe3.txt"));
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
			oos.close();
			fos.close();
			System.out.println(object);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		/**
		 * 反序列化
		 */
		try {
			FileInputStream fis = new FileInputStream(new File("SingletonUnSafe3.txt"));
			ObjectInputStream ois = new ObjectInputStream(fis);
			SingletonUnSafe3 readObject = (SingletonUnSafe3) ois.readObject();
			ois.close();
			fis.close();
			System.out.println(readObject);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}
